#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
typedef pair<int,int> pi;
int a[maxn][maxn];
bool vis[maxn][maxn];
int m, n;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
#if 0
bool bfs(int x) {
#if 0
  for(int i=0; i<n; ++i)
    for(int j=0; j<m; ++j)
      vis[i][j] = (a[i][j] > x);
#endif
  queue<pi> q;
  memset(vis, 0, sizeof(vis));
  q.push({0, 0});
  vis[0][0] = true;
  while(q.size()) {
    auto [xi, yi] = q.front();
    q.pop();
    for(int i=0; i<4; ++i) {
      int nx=xi+dx[i], ny=yi+dy[i];
      if(nx<0||ny<0||nx>=n||ny>=m||vis[nx][ny]||a[nx][nx]>x)
        continue;
      vis[nx][ny] = true;
      if(nx==n-1) {
        return true;
      }
      q.push({nx, ny});
    }
  }
  return false;
}
#else
int bfs(int maxn) //判断mid是否可行的bfs
{
    memset(vis, 0, sizeof(vis));
    for(int i=0; i<n; ++i)
      for(int j=0; j<m; ++j)
        vis[i][j] = (a[i][j]>maxn);
	queue<pi> q;
	q.push({0, 0});
    vis[0][0]=true;
	while(q.size()) { //以下就是bfs板子
        auto [xx, yy] = q.front(); q.pop();
		for(int i = 0; i < 4; i++) {
			int nx = xx + dx[i];
			int ny = yy + dy[i];
			if(nx < 0 || nx >= n || ny < 0 || ny >= m || vis[nx][ny])// || a[nx][ny]>maxn)
				continue;
			vis[nx][ny] = 1;
			if(nx == n-1) return true;
			else q.push({nx, ny});
		}
	}
	return false;
}
#endif

int main() {
#ifndef ONLINE_JUDGE
  freopen("in2.txt", "r", stdin);
#endif
  ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  // cin>>n>>m; // Equally AC???
  cin>>m>>n;
  for(int i=0; i<n; ++i)
    for(int j=0; j<m; ++j)
      cin>>a[i][j];
  int l=0, r=1000;
  int mid = -1;
  int ans = -1;
  while(l<=r) {
    mid = (l+r)/2;
    if(bfs(mid)) ans = mid, r = mid-1;
    else l = mid+1;
  }
  cout<<ans<<'\n';
}
